package com.juyu.miliao.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class VersionCheckUtil {
    /**
     * 比较是否需要更新
     *
     * @param ids     待比较版本
     * @param version 目标版本
     * @return boolean　true-需要  false-不需要
     */
    public static boolean compare(String[] ids, String version) {
        List<Integer> forceIds = splitVersionString(version);
        int var;
        int forceVar;
        boolean flag = true;
        for (int i = 0; i < 3; i++) {
            var = CommonUtil.null2Int(ids[i]);
            forceVar = forceIds.get(i);
            if (var > forceVar) {
                flag = false;
                break;
            }

            if (var == forceVar) {
                if (i == 2) {
                    flag = false;
                }
                continue;
            }

            //比forceVar小
            break;
        }

        return flag;
    }

    /**
     * 版本按.分割
     *
     * @param forceVersion 版本
     * @return List<Integer>
     */
    private static List<Integer> splitVersionString(String forceVersion) {
        List<Integer> list = new ArrayList<>();
        if (!StringUtils.isEmpty(forceVersion)) {
            String[] adrStrings = forceVersion.split("\\.");
            if (adrStrings.length >= 3) {
                list.add(CommonUtil.null2Int(adrStrings[0]));
                list.add(CommonUtil.null2Int(adrStrings[1]));
                list.add(CommonUtil.null2Int(adrStrings[2]));
            }
        }
        return list;
    }
}
